import { apiConfig, getBaseURL, HTTP_STATUS } from './config.js'

// 请求队列，用于管理loading状态
let requestQueue = 0

// 显示loading
const showLoading = () => {
  if (requestQueue === 0) {
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
  }
  requestQueue++
}

// 隐藏loading
const hideLoading = () => {
  requestQueue--
  if (requestQueue <= 0) {
    requestQueue = 0
    uni.hideLoading()
  }
}

// 获取token
const getToken = () => {
  return uni.getStorageSync('accessToken') || ''
}

// 不需要token的接口列表
const noTokenUrls = ['/auth/login', '/user/register']

// 请求拦截器
const requestInterceptor = (options) => {
  // 设置基础URL
  if (!options.url.startsWith('http')) {
    options.url = getBaseURL() + options.url
  }
  
  // 设置默认headers
  options.header = {
    ...apiConfig.headers,
    ...options.header
  }
  
  // 判断是否需要添加token
  const needToken = !noTokenUrls.some(url => options.url.includes(url))
  
  // 添加token（除了登录注册接口）
  if (needToken) {
    const token = getToken()
    if (token) {
      options.header['Authorization'] = `Bearer ${token}`
    }
  }
  
  // 设置超时时间
  options.timeout = options.timeout || apiConfig.timeout
  
  return options
}

// 响应拦截器
const responseInterceptor = (response, originalOptions) => {
  const { data, statusCode } = response
  
  // HTTP状态码处理
  if (statusCode !== HTTP_STATUS.SUCCESS) {
    // 优先使用响应体中的message，如果没有则使用状态码映射
    const responseMessage = data && (data.message || data.msg)
    const errorMessage = responseMessage || apiConfig.errorMessages[statusCode] || `请求失败，状态码：${statusCode}`
    
    // 401需要重新登录
    if (statusCode === HTTP_STATUS.UNAUTHORIZED) {
      uni.removeStorageSync('accessToken')
      uni.removeStorageSync('refreshToken')
      uni.removeStorageSync('userInfo')
      uni.showModal({
        title: '提示',
        content: '登录已过期，请重新登录',
        showCancel: false,
        success: () => {
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }
      })
    } else {
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 2000
      })
    }
    
    return Promise.reject({
      message: errorMessage,
      statusCode,
      data
    })
  }
  
  // 业务状态码处理
  if (data && typeof data === 'object') {
    // 检查业务状态码，0表示成功
    if (data.code !== undefined && data.code !== 0) {
      // 失败时显示响应中的message字段
      const errorMessage = data.message || data.msg || '操作失败'
      
      if (!originalOptions.silent) {
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        })
      }
      
      return Promise.reject({
        message: errorMessage,
        code: data.code,
        data: data.data
      })
    }
    
    // 成功时不自动显示消息，由页面自定义成功提示
    // 返回业务数据，如果有data字段则返回data，否则返回整个响应
    return data.data !== undefined ? data.data : data
  }
  
  return data
}

// 错误处理
const errorHandler = (error, originalOptions) => {
  console.error('请求错误:', error)
  
  let errorMessage = '网络请求失败'
  
  if (error.errMsg) {
    if (error.errMsg.includes('timeout')) {
      errorMessage = '请求超时，请检查网络连接'
    } else if (error.errMsg.includes('fail')) {
      errorMessage = '网络连接失败，请检查网络设置'
    }
  }
  
  if (!originalOptions.silent) {
    uni.showToast({
      title: errorMessage,
      icon: 'none',
      duration: 2000
    })
  }
  
  return Promise.reject({
    message: errorMessage,
    error
  })
}

// 基础请求方法
const request = (options = {}) => {
  return new Promise((resolve, reject) => {
    // 是否显示loading
    if (!options.silent && !options.hideLoading) {
      showLoading()
    }
    
    // 请求拦截
    const requestOptions = requestInterceptor(options)
    
    uni.request({
      ...requestOptions,
      success: (response) => {
        try {
          const result = responseInterceptor(response, options)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        const result = errorHandler(error, options)
        reject(result)
      },
      complete: () => {
        if (!options.silent && !options.hideLoading) {
          hideLoading()
        }
      }
    })
  })
}

// GET请求
export const get = (url, params = {}, options = {}) => {
  // 对于GET请求，将params转换为查询字符串
  let fullUrl = url
  if (params && Object.keys(params).length > 0) {
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    fullUrl += (url.includes('?') ? '&' : '?') + queryString
  }
  
  return request({
    url: fullUrl,
    method: 'GET',
    ...options
  })
}

// POST请求
export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

// PUT请求
export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

// DELETE请求
export const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

// 导出基础请求方法
export { request }

// 默认导出
export default {
  get,
  post,
  put,
  delete: del,
  request
} 